package service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;

import java.lang.ref.WeakReference;

import Constant.Constant;

public class MyService extends Service {

    private Context mContext;
    private final Messenger mMessenger;

    public MyService() {
        mContext = this;
        mMessenger = new Messenger(new MessageHandler(new WeakReference<>(mContext)));
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        Log.i(Constant.TAG,"onDestroy");
        super.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(Constant.TAG,"onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mMessenger.getBinder();
    }

    public static class MessageHandler extends Handler{
        private Context mContext;

        public MessageHandler(WeakReference<Context> reference){
            mContext = reference.get();
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case Constant.MESSAGE_HANDLER_MSG:
                    Messenger replyTo = msg.replyTo;
                    Message mReply = Message.obtain(null,Constant.MESSAGE_REPLY_MSG);
                    Bundle mReplyData = new Bundle();
                    mReplyData.putString("data","hello, this is service");
                    mReply.setData(mReplyData);
                    Bundle data = msg.getData();
                    String data1 = data.getString("data");
                    Log.i(Constant.TAG,data1);
                    try {
                        replyTo.send(mReply);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    }
}
